<?php

namespace app\superpartner\controller;

use app\common\controller\CommonService;
use OSS\OssClient;
use think\Controller;
use think\Db;
use think\facade\Cache;
use think\facade\Validate;
use think\Request;

class Login extends Controller
{


    /**
     * 超级合伙人登录
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login(Request $request)
    {
        $requestData = $request->post();
        $validate = Validate::make([
            'tel|手机号' => 'require|mobile',
            'password|密码' => 'require|min:6'
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $userInfo = Db::name('user_manage')->where('tel', $requestData['tel'])->field('id,nickname,xingming,headimgurl')->find();
        $partner = Db::name('super_partner')->where('uid', $userInfo['id'])->find();
        if (!$partner) {
            return CommonService::error(1);
        }
        switch ($partner['status']) {
            case 0:
                return CommonService::error(10);
            case 1:
                break;
            case 2:
                return CommonService::error('正在审核中！');
            case 3:
                return CommonService::error(11);
            default:
                return CommonService::error(12);
        }

        if ($partner['password'] !== md5($requestData['password'])) {
            return CommonService::error(2);
        }
        Db::name('login_log')->insert([
            'uid' => $partner['id'],
            'login_time' => time(),
            'login_ip' => $request->ip(),
            'login_area' => CommonService::getAttributionByIp($request->ip()),
            'login_browser' => CommonService::getBrowserInfo(request()->header()),
            'user_type' => 1,
        ]);
        $responseData['superPartnerToken'] = CommonService::jwtEncode(['id' => $partner['id']], time() + 86400);
        $responseData['headimgurl'] = $userInfo['headimgurl'];
        $responseData['nickname'] = CommonService::emoji_decode($userInfo['nickname']);
        $responseData['xingming'] = $userInfo['xingming'];
        cache('superPartnerAdmin' . $partner['id'], $responseData['superPartnerToken'], 86400);
        return CommonService::success($responseData);
    }


    /**
     * 激活
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function activate()
    {
        $requestData = request()->post();
        $validate = Validate::make([
            'tel|手机号' => 'require|mobile',
            'code_no|激活码' => 'require|length:16'
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $userId = Db::name('user_manage')->where('tel', $requestData['tel'])->value('id');
        $partner = Db::name('super_partner')->where('uid', $userId)->find();
        if (!$partner) {
            return CommonService::error(1);
        }
        if (!in_array($partner['status'], [2, 3])) {
            return CommonService::error(13);
        }
        $code = Db::name('agent_code')->where(['code_no' => $requestData['code_no'], 'code_type' => 1, 'use_partner_id' => $partner['id']])->find();
        if (!$code) {
            return CommonService::error(14);
        }

        //判断激活码是否被激活
        if (empty($code['use_time'])) {
            Db::name('agent_code')->where('id', $code['id'])->update(['use_time' => time()]);
            return CommonService::success(['page' => 1, 'super_partner_id' => $partner['id']]);
        } else {
            if (empty($partner['password'])) {
                return CommonService::success(['page' => 1, 'super_partner_id' => $partner['id']]);
            } else {
                if (empty($partner['id_no'])) {
                    return CommonService::success(['page' => 2, 'super_partner_id' => $partner['id']]);
                } else {
                    return CommonService::success(['page' => 3, 'super_partner_id' => $partner['id']]);
                }
            }
        }
    }

    /**
     * 发送验证码
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function sendSms()
    {
        $requestData = request()->post();
        $validate = Validate::make([
            'tel|手机号' => 'require|mobile',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $uid = Db::name('user_manage')->where('tel',$requestData['tel'])->value('id');
        $superPartner = Db::name('super_partner')->where('uid', $uid)->find();
        if (empty($superPartner)){
            return CommonService::error(1);
        }
        $templateParam['code'] = mt_rand(1000, 9999);
        $send = CommonService::sendSms($requestData['tel'], $templateParam, 'SMS_175535973');
        if ($send) {
            if (Cache::get('sendSmsCount' . $requestData['tel']) <= 0) {
                $time = strtotime(date('Y-m-d')) + 86400 - time();
                Cache::set('sendSmsCount' . $requestData['tel'], 1, $time);
            } else {
                Cache::inc('sendSmsCount' . $requestData['tel'], 1);
            }
            Cache::set('smsCode' . $requestData['tel'], $templateParam['code'], 300);
            return CommonService::success('', '验证码已发送！');
        } else {
            return CommonService::error(3);
        }
    }
    //验证手机验证码
    public function checkSms()
    {
        $requestData = request()->post();
        $validate = Validate::make([
            'tel|手机号' => 'require|mobile',
            'smscode|验证码' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $userInfo = Db::name('user_manage')->where('tel', $requestData['tel'])->find();
        $superPartnerId = Db::name('super_partner')->where('uid',$userInfo['id'])->value('id');
        if (empty($superPartnerId)){
            return CommonService::error(1);
        }
        if ($requestData['smscode'] != Cache::get('smsCode' . $requestData['tel'])) {
            return CommonService::error(5);
        }
        $data['id'] = $superPartnerId;
        return CommonService::success($data,'验证通过');
    }

    //忘记密码
    public function forgetPassword()
    {
        $requestData = request()->post();
        $validate = Validate::make([
            'password|密码' => 'require',
            'id' => 'require|number'
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $superPartnerInfo = Db::name('super_partner')->where('id',$requestData['id'])->find();
        if ($superPartnerInfo['password'] == md5($requestData['password'])){
            return CommonService::error(108);
        }
        if (empty($superPartnerInfo)){
            return CommonService::error(1);
        }
        $bool = Db::name('super_partner')->where('id', $requestData['id'])->update(['password' => md5($requestData['password'])]);
        if ($bool) {
            return CommonService::success([], 106);
        } else {
            return CommonService::error(0);
        }
    }
    /**
     * 设置密码
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setPassword()
    {
        $requestData = request()->post();
        $validate = Validate::make([
            'password|密码' => 'require|min:6',
            'repassword|重复密码' => 'require|confirm:password',
            'super_partner_id' => 'require|number',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $bool = Db::name('super_partner')->where('id', $requestData['super_partner_id'])->update(['password' => md5($requestData['password'])]);
        if ($bool) {
            return CommonService::success(['page' => 2, 'super_partner_id' => $requestData['super_partner_id']], '设置成功！');
        } else {
            return CommonService::error(0);
        }
    }

    /**
     * 设置认证资料
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setData()
    {
        $requestData = request()->post();
        $validate = Validate::make([
            'real_name|真实姓名' => 'require|chs',
            'id_no|身份证号' => 'require|idCard',
            'id_front_img|身份证正面图' => 'require|url',
            'id_back_img|身份证反面图' => 'require|url',
            'id_hand_img|身份证手持图' => 'require|url',
            'super_partner_id' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        Db::startTrans();
        try {
            Db::name('super_partner')->where('id', $requestData['super_partner_id'])->update([
                'real_name' => $requestData['real_name'],
                'id_no' => $requestData['id_no'],
                'id_front_img' => $requestData['id_front_img'],
                'id_back_img' => $requestData['id_back_img'],
                'id_hand_img' => $requestData['id_hand_img'],
            ]);
            Db::name('partner_check_log')->insert([
                'partner_type' => 1,
                'partner_id' => $requestData['super_partner_id'],
                'check_type' => 1,
                'check_status' => 0,
                'add_time' => time(),
            ]);
            Db::commit();
            return CommonService::success(['page' => 3, 'super_partner_id' => $requestData['super_partner_id']], '设置成功！');
        } catch (\Exception $e) {
            Db::rollback();
            return CommonService::error(0);
        }
    }

    /**
     * 上传身份证图片到OSS
     * @return \think\response\Json
     * @throws \OSS\Core\OssException
     */
    public function uploadIdImg()
    {
        $requestData = request()->post();
        $validate = Validate::make([
            'super_partner_id' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $files = request()->file();
        foreach ($files as $file) {
            if (!$file->check(['size' => 1024000 * 5, 'ext' => 'jpg,jpeg,png,gif'])) {
                return CommonService::error($file->getError());
            }
        }
        switch ($files) {
            case !empty($files['id_front_img']):
                $file = $files['id_front_img'];
                $fileName = $file->getinfo('name');
                $fileName = explode(".", $fileName);
                $fileExt = trim(array_pop($fileName));
                $object = "static/admin/id_front_img{$requestData['super_partner_id']}.{$fileExt}";
                break;
            case !empty($files['id_back_img']):
                $file = $files['id_back_img'];
                $fileName = $file->getinfo('name');
                $fileName = explode(".", $fileName);
                $fileExt = trim(array_pop($fileName));
                $object = "static/admin/id_back_img{$requestData['super_partner_id']}.{$fileExt}";
                break;
            case !empty($files['id_hand_img']):
                $file = $files['id_hand_img'];
                $fileName = $file->getinfo('name');
                $fileName = explode(".", $fileName);
                $fileExt = trim(array_pop($fileName));
                $object = "static/admin/id_hand_img{$requestData['super_partner_id']}.{$fileExt}";
                break;
            default:
                return CommonService::error(15);
        }
        $url = CommonService::uploadOss($file->getinfo('tmp_name'), $object);
        if ($url) {
            return CommonService::success(['url' => $url . '?' . time()]);
        } else {
            return CommonService::error(15);
        }
    }


    /**
     * 审核状态
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkStatus()
    {
        $requestData = request()->post();
        $validate = Validate::make([
            'super_partner_id' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }

        $check = Db::name('partner_check_log')
            ->order('add_time', 'desc')
            ->where([
            'partner_type' => 1,
            'partner_id' => $requestData['super_partner_id'],
            'check_type' => 1,
        ])->find();
        if (empty($check)) {
            return CommonService::error(12);
        }
        $data['check_status'] = $check['check_status'];
        $data['cause'] = $check['cause'];
        $data['check_time'] = $check['check_time'];
        return CommonService::success($data);
    }
}
